<template>
  <div class="app-container">
        <!-- 统计信息 -->
        <el-card class="box-card mb20">
      <div class="statistics-container">
        <div class="stat-item">
          <span class="label">合同总数</span>
          <span class="value">{{ stats.total || 0 }}</span>
        </div>
        <el-divider direction="vertical"></el-divider>
        <div class="stat-item">
          <span class="label">处理中</span>
          <span class="value warning-text">{{ stats.uploadingCount + stats.analyzingCount || 0 }}</span>
        </div>
        <el-divider direction="vertical"></el-divider>
        <div class="stat-item">
          <span class="label">已完成</span>
          <span class="value success-text">{{ stats.completedCount || 0 }}</span>
        </div>
        <el-divider direction="vertical"></el-divider>
        <div class="stat-item">
          <span class="label">失败</span>
          <span class="value danger-text">{{ stats.failCount || 0 }}</span>
        </div>
        <el-divider direction="vertical"></el-divider>
        <div class="stat-item">
          <span class="label">风险分布</span>
          <span class="risk-distribution">
            <el-tag size="mini" type="success">低:{{ stats.lowRiskCount || 0 }}</el-tag>
            <el-tag size="mini" type="warning">中:{{ stats.mediumRiskCount || 0 }}</el-tag>
            <el-tag size="mini" type="danger">高:{{ stats.highRiskCount || 0 }}</el-tag>
          </span>
        </div>
      </div>
    </el-card>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="合同标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入合同标题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="合同类型" prop="contractType">
        <el-input v-model="queryParams.contractType" placeholder="请输入合同类型" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="合同状态" clearable>
          <el-option label="上传中" value="0"/>
          <el-option label="分析中" value="1"/>
          <el-option label="已完成" value="2"/>
          <el-option label="失败" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:contract:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="合同编号" align="center" prop="id"/>
      <el-table-column label="合同标题" align="center" prop="title"/>
      <el-table-column label="用户名称" align="center" prop="userName" width="120"/>
      <el-table-column label="合同类型" align="center" prop="contractType">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.contractType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="风险等级" align="center" prop="riskLevel">
        <template slot-scope="scope">
          <el-tag :type="scope.row.riskLevel === 0 ? 'success' : scope.row.riskLevel === 1 ? 'warning' : 'danger'">
            {{ scope.row.riskLevel === 0 ? '低风险' : scope.row.riskLevel === 1 ? '中风险' : '高风险' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'warning' : scope.row.status === 2 ? 'primary' : scope.row.status === 3 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '上传中' : scope.row.status === 2 ? '分析中' : scope.row.status === 3 ? '已完成' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['system:contract:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:contract:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 查看合同详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body custom-class="view-dialog">
      <el-descriptions class="contract-info" :column="2" border>
        <el-descriptions-item label="合同标题">{{ form.title }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ form.userName }}</el-descriptions-item>
        <el-descriptions-item label="合同类型">
          <el-tag size="medium">{{ form.contractType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag :type="form.riskLevel === '0' ? 'success' : form.riskLevel === '1' ? 'warning' : 'danger'" size="medium">
            {{ form.riskLevel === '0' ? '低风险' : form.riskLevel === '1' ? '中风险' : '高风险' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ parseTime(form.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ form.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="合同文件" :span="2">
          <div class="file-grid" v-if="form.filePath">
            <div v-for="(url, index) in filePathList" :key="index" class="file-card">
              <!-- 图片文件显示缩略图 -->
              <template v-if="isImage(url)">
                <div class="image-container">
                  <img :src="url" class="preview-image">
                </div>
                <div class="file-info">
                  <span class="file-name">{{ getFileName(url) }}</span>
                  <span class="file-type">图片文件</span>
                </div>
              </template>
              <!-- 非图片文件显示图标 -->
              <template v-else>
                <div class="doc-container">
                  <i class="el-icon-document"></i>
                </div>
                <div class="file-info">
                  <span class="file-name">{{ getFileName(url) }}</span>
                  <span class="file-type">文档文件</span>
                </div>
              </template>
            </div>
          </div>
          <div v-else class="no-files">暂无文件</div>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
  getContractStats
} from "@/api/system/contract";

export default {
  name: "Contract",
  dicts: ['contract_type'],
  data() {
    return {
      // 统计数据
      stats: {
        total: 0,
        uploadingCount: 0,
        analyzingCount: 0,
        completedCount: 0,
        failCount: 0,
        lowRiskCount: 0,
        mediumRiskCount: 0,
        highRiskCount: 0
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同表格数据
      contractList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        userName: undefined,
        contractType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 文件列表
      fileList: [],
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/contract/upload",
      // 表单校验
      rules: {
        title: [
          { required: true, message: "合同标题不能为空", trigger: "blur" }
        ],
        contractType: [
          { required: true, message: "合同类型不能为空", trigger: "blur" }
        ],
        riskLevel: [
          { required: true, message: "风险等级不能为空", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    filePathList() {
      return this.form.filePath ? this.form.filePath.split(',').filter(url => url) : [];
    }
  },
  created() {
    this.getList();
    this.getStats();
  },
  methods: {
    /** 获取统计信息 */
    getStats() {
      getContractStats().then(response => {
        this.stats = response.data;
      });
    },
    /** 查询合同列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        userId: undefined,
        userName: undefined,
        contractType: undefined,
        riskLevel: undefined,
        filePath: undefined,
        remark: undefined
      };
      this.resetForm("form");
      this.fileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.userId = this.$store.state.user.userId;  // 设置当前用户ID
      this.form.userName = this.$store.state.user.nickName;  // 设置当前用户名称
      this.open = true;
      this.title = "添加合同";
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      getContract(id).then(response => {
        this.form = response.data;
        if (this.form.filePath) {
          this.fileList = this.filePathList.map(url => ({
            name: this.getFileName(url),
            url: url
          }));
        }
        this.open = true;
        this.title = "查看合同";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同编号为"' + ids + '"的数据项？').then(function() {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 文件上传成功处理
    handleUploadSuccess(response, file, fileList) {
      const newUrl = response.data;
      if (this.form.filePath) {
        this.form.filePath = this.form.filePath + ',' + newUrl;
      } else {
        this.form.filePath = newUrl;
      }
      this.$modal.msgSuccess("上传成功");
    },
    // 文件删除前的钩子
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.form.filePath = undefined;
    },
    // 判断是否为图片
    isImage(url) {
      return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
    },
    // 获取文件名
    getFileName(url) {
      const parts = url.split('/');
      return parts[parts.length - 1];
    },
    // 移除单个文件
    removeFile(index) {
      const files = this.filePathList;
      files.splice(index, 1);
      this.form.filePath = files.join(',');
    }
  }
};
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.statistics-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 15px;
}

.stat-item .label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-item .value {
  font-size: 20px;
  font-weight: bold;
}

.warning-text {
  color: #E6A23C;
}

.success-text {
  color: #67C23A;
}

.danger-text {
  color: #F56C6C;
}

.risk-distribution {
  display: flex;
  gap: 5px;
  margin-top: 5px;
}

.el-divider--vertical {
  height: 40px;
  margin: 0;
}

.file-list {
  margin-bottom: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
}

.file-link {
  display: flex;
  align-items: center;
  color: #606266;
  margin-right: 10px;
}

.file-link i {
  margin-right: 5px;
}

.view-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.contract-info {
  margin-bottom: 20px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 10px;
}

.file-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  background: #fff;
  height: 220px;
  display: flex;
  flex-direction: column;
}

.file-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.image-container {
  height: 160px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.doc-container {
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.doc-container i {
  font-size: 60px;
  color: #909399;
}

.file-info {
  padding: 10px;
  border-top: 1px solid #EBEEF5;
  background: #fff;
}

.file-name {
  display: block;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-type {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.no-files {
  color: #909399;
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>